//
//  RiddingAppDelegate.m
//  Ridding
//
//  Created by zys on 12-3-19.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "RiddingAppDelegate.h"
#import "LandingViewController.h"
#import "StaticInfo.h"
#import "QQNRFeedViewController.h"
#import "ResponseCodeCheck.h"
#import "MobClick.h"
#import "RequestUtil.h"
#import "SqlUtil.h"
@implementation RiddingAppDelegate
@synthesize window = _window;
@synthesize rootViewController = _rootViewController;
@synthesize navController=_navController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
    [MobClick startWithAppkey:YouMenAppKey reportPolicy:REALTIME channelId:nil];
    [MobClick checkUpdate];
  });
  [self initGolbalValue];
  [[ResponseCodeCheck getSinglton] checkConnect];
  //检查网络
  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  self.navController = [[UINavigationController alloc]init];

  [self setUserInfo];
  self.rootViewController = [[RiddingViewController alloc]init];
  [self.navController pushViewController:self.rootViewController animated:NO];
  if([self canLogin]){
    [[RequestUtil getSinglton] sendApns];
    //如果新浪成功，并且authtoken有效
    QQNRFeedViewController *FVC=[[QQNRFeedViewController alloc]initWithUser:[StaticInfo getSinglton].user exUser:nil];
    FVC.isMyFeedHome=TRUE;
    [self.navController pushViewController:FVC animated:NO];
    [StaticInfo getSinglton].logined=true;
  }
  self.navController.navigationBar.hidden=YES;
  self.window.rootViewController = self.navController;
  [self.window makeKeyAndVisible];
  
  return YES;
}


- (void)initGolbalValue{
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSString *versionStr = [[[NSBundle mainBundle]infoDictionary ]objectForKey:(NSString*)kCFBundleVersionKey];
  //1.1版本增加字段
  if ([versionStr isEqualToString:@"1.1"]&&![defaults objectForKey:@"updated"]) {
    [[SqlUtil getSinglton]readyDatabse];
    BOOL succ= [[SqlUtil getSinglton]dealData:@"ALTER TABLE riddingpicture ADD COLUMN text varchar(512)" paramArray:nil];
    if(succ){
      [defaults setValue:@"true" forKey:@"updated"];
    }
  }
}

-(void)setUserInfo{
  StaticInfo *staticInfo=[StaticInfo getSinglton];
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  staticInfo.user.userId = [prefs stringForKey:@"userId"];
  staticInfo.user.authToken=[prefs stringForKey:@"authToken"];
  staticInfo.user.accessUserId = [prefs stringForKey:@"accessUserId"];
  staticInfo.user.accessToken=[prefs stringForKey:@"accessToken"];
  staticInfo.user.sourceType = [prefs integerForKey:@"sourceType"];
}

-(bool)canLogin{
    StaticInfo* staticInfo=[StaticInfo getSinglton];
    RequestUtil* requestUtil=[RequestUtil getSinglton];
    NSDictionary *userProfileDic = [requestUtil getUserProfile:staticInfo.user.userId sourceType:staticInfo.user.sourceType];
    //如果新浪成功，并且authtoken有效
    if(staticInfo.user.accessToken!=nil&&userProfileDic!=nil){
        staticInfo.user.name=[userProfileDic objectForKey:@"nickname"];
        staticInfo.user.bavatorUrl=[userProfileDic objectForKey:@"bavatorurl"];
        staticInfo.user.savatorUrl=[userProfileDic objectForKey:@"savatorurl"];
        staticInfo.user.totalDistance=[userProfileDic objectForKey:@"totalDistance"];
        staticInfo.user.nowRiddingCount=[[userProfileDic objectForKey:@"riddingCount"]intValue];
        return true;
    }
    return false;
}

- (NSString*)getPlist:(NSString*)key{
  NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectoryPath = [paths objectAtIndex:0];
  NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"Ridding-Info.plist"];
  NSMutableDictionary *DictPlist = [NSDictionary dictionaryWithContentsOfFile: path];
  NSLog(@"%@",DictPlist);
  return [DictPlist objectForKey:key];
}


//iPhone 从APNs服务器获取deviceToken后回调此方法
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSString* dt = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  [prefs setObject:dt forKey:@"apnsToken"];
}

//注册push功能失败 后 返回错误信息，执行相应的处理
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

@end
